<?php
/*************************************************

推手公共控制器 - the
Author: Reload <17-10-24>

*************************************************/
namespace Home\Controller;
use Think\Controller;
class RecommendController extends CommonController {
    public function apply_pusher() {
        $this->display();
    }


    //推手申请(未实名)
    public function apply_pusher_form() {
            if(!$_SESSION['user']['id']){
                header("location:/Home/User/login");
            }
        if(IS_POST){
			
            $is_pass=0;
            $realname = I('post.name');
            $idcard = I('post.idcard');
            $phone = $_SESSION['user']['user_phone'];
            $where['id'] = $_SESSION['user']['id'];
            $user_info  = D('User')->get_one($where);
            if($user_info['card_status']==1){
                if($user_info['idcard']==$idcard && $user_info['realname']==$realname){
                    $is_pass=1;
                }
            }
            if(!$is_pass){
                $res = $this->realname($realname,$idcard,1);
				
            }
            if($res['err']==1 or $is_pass==1){
                $map['user_id'] = $_SESSION['user']['id'];
                $res = D('RecommendApply')-> get_one($map);
                if($res){
                    $data = array('err'=>2,'msg'=>'您已申请过了不要重复申请！');
                }else{
                    $arr['name'] = $realname;
                    $arr['tel'] = $phone;
                    $arr['user_id'] = $_SESSION['user']['id'];
                    $arr['status'] =0;
                    $r = D('RecommendApply')->add($arr);
					
                   if($r){
                        $data = array('err'=>0,'msg'=>'申请提交成功');
                    }else{
                        $data = array('err'=>1,'msg'=>'提交失败请重试！');
                    }
               }
            }else{
			
                $data = $res;
            }
            $this->ajaxReturn($data);
        } else {
            $user_id = $_SESSION['user']['id'];
            $map['id'] = $user_id;
            $user = D('User')->get_one($map);
            $card_status = $user['card_status'];
             if($card_status){
                 header('location:/Home/Recommend/push_apply');
             }
            $this->assign('user',$user);
            $this->display();
        }
    }
    //推手申请（已实名）
    public function push_apply(){
            if(!$_SESSION['user']['id']){
                header("location:/Home/User/login");
            }
        if(IS_POST){
            $postdata = I('post.');
            $postdata['tel'] = $_SESSION['user']['user_phone'];
            $postdata['user_id'] = $_SESSION['user']['id'];
            $postdata['add_time'] = time();
            $map['user_id'] = $_SESSION['user']['id'];
            $res = D('RecommendApply')-> get_one($map);
               if(!$res){
                    $map = array();
                    $map['tel'] = $_SESSION['user']['user_phone'];
                    $r = D('RecommendApply')-> get_one($map);
                    if($r){
                        $res = true;
                    }else{
                        $res = false;
                    }
                }
               if($res){
                    $data = array('err'=>2,'msg'=>'您已申请过了不要重复申请！');
               }else{
                   $r = D('RecommendApply')->add($postdata);

                   if($r){
                    //    R('Msg/sendmail',array($typename='jx_push_apply',$userid = $_SESSION['user']['id']));
                        $data = array('err'=>0,'msg'=>'申请提交成功');
                    }else{
                        $data = array('err'=>1,'msg'=>'提交失败请重试！');
                    }
               }
                $this->ajaxReturn($data);
        }else{
            $user_id = $_SESSION['user']['id'];
            $map['id'] = $user_id;
            $user = D('User')->get_one($map);
            $card_status = $user['card_status'];
             if(!$card_status){
                 header('location:/Home/Recommend/apply_pusher_form');
             }
            $this->assign('user',$user);
            $this->display();
           
        }

    }
    //检查推手是否已经申请过
    public function ajax_push_reg() {
        $user_id = I('post.user_id');
        $map['user_id'] = $user_id;
        $recom_apply = D('RecommendApply')->get_one($map);
        if($recom_apply) {
            $data = array('err'=>1,'msg'=>"您已申请过了,请等待审核！");
        } else {
            $data = array('err'=>0);
        }
        $this->ajaxReturn($data);
    }



    //实名
    public function realname($realname,$idcard,$val=0){
        if(!$realname && !$idcard){
            $realname = I('post.realname');
            $idcard = I('post.idcard');
        }
        

        $map['idcard'] = $idcard;
        $idcards = D('User')->get_one($map);
        if($idcards) {
            $data = array(
                    'err' => 8,
                    'msg' => "身份证已被绑定"
                );
                if($val){
                 return $data;
                }else{
                 $this->ajaxReturn($data);
                }
        }


         if(empty($realname)) {
            $data = array(
                'err' => 7,
                'msg' => "名字不能为空"
            );
            if($val){
                 return $data;
            }else{
                 $this->ajaxReturn($data);
            }
        }
        if(empty($idcard)) {
            $data = array(
                'err' => 9,
                'msg' => "身份证号码不能为空"
            );
            if($val){
                 return $data;
            }else{
                 $this->ajaxReturn($data);
            }
        }
        $map['user_id'] = $_SESSION['user']['id'];
        $re = M('Realname')->where($map)->find();
		
        if($re){
                $add_day = date('ymd',$re['add_time']);
                $num = $re['num'];
                $today = date('ymd',time());
                    if($num>=5){
                        if($today==$add_day){
                            $data = array(
                                'err' => 4,
                                'msg' => "今天验证次数已经超过5次！明天再来！"
                            );
                        }else{
                            //验证
                            $data =$this->get_real($idcard,$realname);
                            if($data['err']!=3){
                                $arr_data = array('num'=>1,'add_time'=>time());
                                $map['id'] = $re['id'];
                                $r = M('Realname')->where($re['id'])->save($arr_data);
                            }else{
								
								$this->ajaxReturn($data);
							}
                            
                        }
						
                    }else{
						
                            $num = $num+1;
                            $number = 5-$num;
                            $data =$this->get_real($idcard,$realname,$number);
							
                            if($data['err']!=3){
                                $arr_data = array('num'=>$num,'add_time'=>time());
                                $map['id'] = $re['id'];
                                $r = M('Realname')->where($re['id'])->save($arr_data);
                            }else{
								
								$this->ajaxReturn($data);
							}
                            
                    }

        }else{
                        $data = $this->get_real($idcard,$realname);
                        if($data['err']!=3){
                            $arr_data = array('num'=>1,'add_time'=>time(),'user_id'=>$_SESSION['user']['id']);
                            $r = M('Realname')->data($arr_data)->add();
                        }
        }
		
        if($val){
            return $data;
        }else{
            $this->ajaxReturn($data);
        }

    }



     public function get_real($idcard,$realname,$number='4'){
 
        // $this->load->library('Real');
        $real =R('Real/v_real',array($idcard,$realname));
		//echo $real;
     //$real = '{"reason": "成功1","result": {"realname": "董好帅","idcard": "330329199001020012","res": 1 },"error_code": 0}';
		//$real = json_decode($real,true);
		//print_r($real);die; 
    if($real['error_code']==0){
        if($real['error_code']=='0') {

           if($real['result']['res']==1){
                $data = array(
                    'err' => 1,
                    'msg' => "验证成功！"
                );
                //写入用户数据
                $id = $_SESSION['user']['id'];
                $map['id'] = $id;
                $arr_data = array(
                    'realname' => $realname,
                    'idcard'   => $idcard,
                    'card_status' => 1
                );
                $user =D('User')->edit($map,$arr_data);
                //實名成功發送消息
            //    R('Msg/sendmail',array($typename='realname',$userid = $id));
                $_SESSION['user']['realname'] = $realname;
                $_SESSION['user']['idcard'] = $idcard;
                $_SESSION['user']['card_status'] = 1;
           }else{
                 $data = array(
                    'err' => 2,
                    'msg' => "验证失败，还剩".$number."次机会"
                );
           }
        } else {
            $data = array(
                'err' => 3,
                'msg' =>$real['reason']
            );
        }
    }else{
                $data = array(
                    'err' => 3,
                    'msg' => "验证请求失败！"
                );
    }
        return($data);


    }


    //推手專區
    public function push_list(){
        //查詢推手信息
        $id = $_SESSION['user']['id'];
        $map['user_id'] = $id;
        $recommend = D('Recommend')->get_one($map);
        if($recommend){
             //查詢所有平台
            $map = array();
            $map['status'] = 0;
            $platform = D('Platform')->get_all($map);
            foreach ($platform as $k => $v) {
               $platform_id = $v['id'];
               //查詢該平台是否被認領
               $map=array();
               $map['recommend_id'] = $recommend['id'];
               $map['platform_id'] = $platform_id;
               $r = D('RecommendPlatform')->get_one($map);
               //echo D('RecommendPlatform')->_sql();
               if($r){
                    $platform[$k]['is_get'] = 1;
               }else{
                    $platform[$k]['is_get'] = 0;
               }
               
            }
            //print_r($platform);
            $this->assign('platform',$platform);
        }else{
            header("Location:/");
        }
       
        $this->display();
    }

     //推手申请平台合作
    public function apply_platfrom(){
        $user_id = $_SESSION['user']['id'];
        $platform_id = I('post.platform_id');
        $map['user_id'] = $user_id;
        $recommend_info = D('Recommend')->get_one($map);
        $recommend_id = $recommend_info['id'];
        $data['recommend_id'] = $recommend_id;
        $data['platform_id'] = $platform_id;
        $data['status'] = 1;
        $data['add_time'] =time();
        $r = D('RecommendPlatform')->add($data);
            if($r){
                R('Msg/sendmail',array($typename='apply_platfrom',$userid = $_SESSION['user']['id']));
                $data = array('err'=>0,'msg'=>"申请成功！");
            }else{
                $data = array('err'=>0,'msg'=>"申请失败！");
            }
        $this->ajaxReturn($data);
    }


    //通过
    public function apply_pusher_success() {
        $this->display();
    }

    //不通过
    public function apply_pusher_error() {
        $this->display();
    }

    //推手申明
    public function apply_pusher_notice() {
        $this->display();
    }



   
        //营销页
    public function m_marketing(){
        $recommend_id = I('get.recommend_id');
        $map['user_id'] = $recommend_id;
        $recommend = D('Recommend')->get_one($map);
        $user_id = $recommend['user_id'];
        
        $map['id'] = $user_id;
        $u_info = D('User')->get_one($map);
      
        $map = array();
        $map['status'] = 0;
        $platform = D('Platform')->where($map)->order('user_award desc')->select();
        
        $signPackage = $this->getSignPackage();

        $this->assign('signPackage',$signPackage);

        $this->assign('platform',$platform);
        $this->assign('u_info',$u_info);
        $this->display();

    }


    /**
     * [recommend_fllow description] 关注投顾
     * @return [type]               [description]
     */
    public function recommend_fllow(){
        $userid = $_SESSION['user']['id'];
        if(!$userid){
            $data = array('err'=>2,'msg'=>"请先登录！");
            $this->ajaxReturn($data);exit;
        }
        $maps['id'] = $userid;
        $user =D('User')->get_one($maps);
        if($user['role']==2) {
         $data = array('err'=>3,'msg'=>"投顾无法拜师！");
         $this->ajaxReturn($data);exit;
        } else {
            $recommend_id = I('post.recommend_id');
            $map['id'] = $recommend_id;
            $recom = D('Recommend')->get_one($map);
            if($recom) {
                if($user['referral']>0) {
                    $data = array('err'=>4,'msg'=>"已拜过师！");
                    $this->ajaxReturn($data);
                } else {
                    $postdata['referral'] = $recom['user_id'];
                    $map = array();
                    $map['id'] = $userid;
                    $res = D('User')->edit($map,$postdata);
                //    echo D('User')->_sql();die;
                    if($res) {
                        $map = array();
                        $map['id'] = $recom['user_id'];
                        M('User')->where($map)->setInc('score',50);
                        $user_recom = D('User')->get_one($map,$field="id,nickname");
                        $map = array();
                        $map['id'] = $userid;
                        M('User')->where($map)->setInc('score',50);
                        $user_info = D('User')->get_one($map,$field="id,score");
						$_SESSION['user']['referral'] = $recom['user_id'];
                        $u = array('user_recom'=>$user_recom,'user_info'=>$user_info);
                        $data = array('err'=>0,'msg'=>"拜师成功",'u'=>$u);
                    } else {
                        $data = array('err'=>1,'msg'=>"拜师失败");
                    }
                }
            }
            $this->ajaxReturn($data);
        }

    }
   public function push_hand(){
	    $signPackage = $this->getSignPackage();
           // print_r($obj_one);
            $this->assign('signPackage',$signPackage);
        $this->display();
    }
     public function getSignPackage() {

    $jsapiTicket = $this->getJsApiTicket();

    $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

    $timestamp = time();

    $nonceStr = $this->createNonceStr();

    // 这里参数的顺序要按照 key 值 ASCII 码升序排序

    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

    $signature = sha1($string);

    $signPackage = array(

      "appId"     =>'wxc3926d97e0dbcf4e',

      "nonceStr"  => $nonceStr,

      "timestamp" => $timestamp,

      "url"       => $url,

      "signature" => $signature,

      "rawString" => $string

    );

    return $signPackage; 

  }

  public function createNonceStr($length = 16) {

    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    $str = "";

    for ($i = 0; $i < $length; $i++) {

      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);

    }

    return $str;

  }

  public function getJsApiTicket() {

    // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例

    $data = json_decode(file_get_contents("jsapi_ticket.json"));

    if ($data->expire_time < time()) {

      $accessToken = $this->getAccessToken();

      $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";

      $res = json_decode($this->httpGet($url));

      $ticket = $res->ticket;

      if ($ticket) {

        $data->expire_time = time() + 7000;

        $data->jsapi_ticket = $ticket;

        $fp = fopen("jsapi_ticket.json", "w");

        fwrite($fp, json_encode($data));

        fclose($fp);

      }

    } else {

      $ticket = $data->jsapi_ticket;

    }

    return $ticket;

  }

  public function getAccessToken() {

    // access_token 应该全局存储与更新，以下代码以写入到文件中做示例

    $data = json_decode(file_get_contents("access_token.json"));

    if ($data->expire_time < time()) {

      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxc3926d97e0dbcf4e&secret=41650eab872ae4d4ef897deb1434c074";

      $res = json_decode($this->httpGet($url));
      //print_r($res);die;
      $access_token = $res->access_token;

      if ($access_token) {

        $data->expire_time = time() + 7000;

        $data->access_token = $access_token;

        $fp = fopen("access_token.json", "w");

        fwrite($fp, json_encode($data));

        fclose($fp);

      }

    } else {

      $access_token = $data->access_token;

    }

    return $access_token;

  }

  public function httpGet($url) {

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($curl, CURLOPT_TIMEOUT, 500);

    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

    curl_setopt($curl, CURLOPT_URL, $url);

    $res = curl_exec($curl);

    curl_close($curl);

    return $res;

  }

  

    //创建门派
    public function factions_idcard() {
        $user = $_SESSION['user']['id'];
        if(!$user){
            header("location:/Home/User/login");
        }
        if(IS_POST) {
            $is_pass = 0;
            $realname = I('post.realname');
            $idcard = I('post.idcard');
            $where['id'] = $user;
            $user_info  = D('User')->get_one($where);
            if($user_info['card_status']==1){
                if($user_info['realname']==$realname){
                    $is_pass=1;
                }
            }
            if($is_pass){
                $_SESSION['push']['realname'] = $realname;
                if($realname) {
                    $data = array('err'=>0);
                }
            }else{
                //校验
                $res = $this->realname($realname,$idcard,1);
                if($res['err']){
                    $map['user_id'] = $user;
                    $res = D('RecommendApply')-> get_one($map);
                    if($res){
                        $data = array('err'=>3,'msg'=>'您已申请过了不要重复申请！');
                    }else{
                        $_SESSION['push']['realname'] = $realname;
                        $_SESSION['push']['idcard'] = $idcard;
                        if($realname && $idcard) {
                            $data = array('err'=>0);
                        }
                    }
                }else{
                    $data = $res;
                }
            }
                $this->ajaxReturn($data);
        } else {
            $map['id'] = $user;
            $user = D('User')->get_one($map);
            $this->assign('user',$user['card_status']);
            $this->display();
        }
    }


    //投顾选择踩雷次数
    public function factions_thunder() {
        $user = $_SESSION['user']['id'];
        if(!$user){
            header("location:/Home/User/login");
        }
        if(IS_POST) {
            $platform_num = I('post.platform_num');
            $year = I('post.year');
            $pit_num = I('post.pit_num');
            $introduce = I('post.introduce');
            if($platform_num) {
                $_SESSION['push']['platform_num'] = $platform_num;
            }
            if($year) {
                $_SESSION['push']['year'] = $year;
            }
            if($pit_num) {
                $_SESSION['push']['pit_num'] = $pit_num;
            }
            if($introduce) {
                $_SESSION['push']['introduce'] = $introduce;
            }
            if($platform_num && $year && $introduce) {
                $data = array('err'=>0);
            }
			//echo $pit_num;
            $this->ajaxReturn($data);
        } else {
            $this->display();
        }
    }


    //门派派系
	public function matial() {
        $user = $_SESSION['user']['id'];
        if(!$user){
            header("location:/Home/User/login");
        }
        if(IS_POST) {
            $factions = I('post.factions');
            $skill = I('post.skill');
            if($factions==1) {
                $factions = "撸毛派";
            } elseif($factions==2) {
                $factions = "稳健派";
            } elseif($factions==3) {
                $factions = "高利派";
            } elseif($factions==4) {
                $factions = "短期派";
            } elseif($factions==5) {
                $factions = "长期派";
            }
            foreach($skill as $k => $v) {
                if($v==1) {
                    $skill[$k] = '避雷神针';
                } elseif($v==2) {
                    $skill[$k] = '活动高手';
                } elseif($v==3) {
                    $skill[$k] = '平台监控';
                } elseif($v==4) {
                    $skill[$k] = '资产配置';
                } elseif($v==5) {
                    $skill[$k] = '野鸡杀手';
                }
            }
            if($skill) {
                $skill['skill'] = implode(',',$skill);
                $skill['user_id'] = $user;
                $s = M('Skill')->data($skill)->add();
            }
            if($factions) {
                $factions['factions']= implode(',',$skill);
                $factions['user_id'] = $user;
                $f = M('Factions')->data($factions)->add();
            }
            if($_SESSION['platform_num'] && $_SESSION['year'] && $_SESSION['pit_num'] && $_SESSION['introduce']) {
                $data['platform_num'] = $_SESSION['platform_num'];
                $data['year'] = $_SESSION['year'];
                $data['pit_num'] = $_SESSION['pit_num'];
                $data['introduce'] = $_SESSION['introduce'];
                $data['tel'] = $_SESSION['user']['user_phone'];
                $data['user_id'] = $_SESSION['user']['id'];
                $data['name'] = $_SESSION['push']['realname'];
                $data['status'] =0;
                $recom = D('RecommendApply')->add($data);
            }
                if($recom && $s && $f){
                    $res = array('err'=>0,'msg'=>'申请提交成功');
                }else{
                    $res = array('err'=>1,'msg'=>'提交失败请重试！');
                }
            $this->ajaxReturn($res);


        } else {
            $this->display();
        }
    }
  
  
  

}